<template>
  <el-dialog
    v-model="dialogVisible"
    append-to-body
    destroy-on-close
    width="60%"
    :close-on-click-modal="false"
  >
    <template #header="{ titleId, titleClass }">
      <div class="dialog-header-with-action">
        <span :id="titleId" :class="titleClass">同步定性结果</span>
        <el-button type="primary" @click="handleConfirmSync">
          确认同步
        </el-button>
      </div>
    </template>
    <UnknownAnalysisResult :tbflag="true" :projectId="projectId" />
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import UnknownAnalysisResult from '@/views/project/list/UnknownAnalysisResult.vue'
import { ProjectApi } from '@/api/dk/project'
import { ElMessage } from 'element-plus'

interface Props {
  modelValue: boolean
  projectId?: string | number
  jobSurveyRef?: any
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'sync-completed'): void
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  projectId: undefined,
  jobSurveyRef: undefined
})

const emit = defineEmits<Emits>()

const dialogVisible = ref(false)

// 监听外部传入的 modelValue 变化
watch(
  () => props.modelValue,
  (newValue) => {
    dialogVisible.value = newValue
  },
  { immediate: true }
)

// 监听内部 dialogVisible 变化，同步到外部
watch(dialogVisible, (newValue) => {
  emit('update:modelValue', newValue)
})

// 处理确认同步
const handleConfirmSync = async () => {
  if (!props.projectId) {
    ElMessage.error('项目ID不能为空')
    return
  }

  try {
    const data = await ProjectApi.synchronizationUnknownAnalysisResult(props.projectId)
    console.log('synchronizationUnknownAnalysisResult:', JSON.stringify(data))

    // 将同步结果传递给JobSurvey组件
    if (data && Array.isArray(data) && props.jobSurveyRef?.value) {
      // 调用JobSurvey组件的添加危害方法
      await props.jobSurveyRef.value.addHazardsFromSyncResults(data)
    }

    // 关闭弹窗
    dialogVisible.value = false

    // 通知父组件同步完成
    emit('sync-completed')

    ElMessage.success('同步完成')
  } catch (error) {
    console.error('同步失败:', error)
    ElMessage.error('同步失败，请稍后重试')
  }
}
</script>

<style scoped>
/* 弹窗标题栏：左侧标题，右侧操作按钮 */
.dialog-header-with-action {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}
</style>
